<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
require_once 'includes/connect.php';
require_once 'includes/function.php';

$db = new myDBS();

$task = $_REQUEST["task"];
$pet_date = $_REQUEST["pet_date"];
$comments = $_REQUEST["comments"];
$borrow_id = $_REQUEST["borrow_id"];

$pet_id = $_REQUEST["pet_id"];

$cash = $_REQUEST["cash"];

$return_date = $_REQUEST["return_date"];
$return_amount = $_REQUEST["return_amount"];

$cancel_date = $_REQUEST["cancel_date"];
$cancel_reason = $_REQUEST["cancel_reason"];


switch ($task) {
    case "new":
        $budget_year = date("Y");

        //$db = new myDBS();
        $pet_id = $db->get_running($budget_year);

        $sql = "INSERT  INTO tbl_pet_borrow (borrow_id, pet_id, pet_date, comments) "
                . " VALUES ('$borrow_id' "
                . " , '$pet_id' "
                . " , '$pet_date' "
                . " , '$comments' "
                . ")";
        //echo $sql;

        echo $pet_id;
        $db->runSQL($sql) or die(mysql_error());

        break;
    case "return":
        $type = "borrow";
        
        $pet_return_id = $db->get_running($budget_year);

        $sql = "INSERT INTO tbl_return (return_date, return_amount, type, borrow_id, pet_id, pet_return_id, remain_cash) "
                . " VALUES ('$return_date', '$return_amount', '$type', '$borrow_id', '$pet_id', '$pet_return_id', '$cash')";

        //echo $sql;
        $db->runSQL($sql) or die(mysql_error());

        if ($cash) {
            $sql = "UPDATE tbl_promise_borrow SET remain = 0 "
                . " WHERE borrow_id = '$borrow_id'";
        } else {
            $sql = "UPDATE tbl_promise_borrow SET remain = remain - $return_amount "
                . " WHERE borrow_id = '$borrow_id'";
        }
        
        
//        $sql = "UPDATE tbl_promise_borrow SET remain = remain - $return_amount "
//                . " WHERE borrow_id = '$borrow_id'";
        $db->runSQL($sql) or die(mysql_error());


        break;

    case "cancel":
        $sql = "UPDATE tbl_pet_borrow "
                . " SET cancel_date = '$cancel_date', "
                . " cancel_reason = '$cancel_reason', "
                . " status = 'cancel' "
                . " WHERE pet_id = '$id'";
        //echo $sql;

        $db->runSQL($sql) or die(mysql_error());

        break;

    default:
        break;
}
?>

